<template>
	<uni-list>
		<uni-list v-for="item in datas.data" :key="item._id" :border="true">
			<!-- 头像显示角标 -->
		<uni-list-chat v-if="item._id !== userid " @click="handlepath(item)" clickable="true" :title="item.username" :avatar="item.avater"
				note="您收到一条新的消息" time="2020-02-02 20:20" badge-positon="left" :badge-text="item.total"></uni-list-chat>
		</uni-list>
	</uni-list>

</template>

<script>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'

	export default {

		setup() {
			let datas = reactive({
				data: []
			})
			let userid = ref('')
			onMounted(() => {
				uni.getStorage({
					key: 'user',
					success: function(res) {
						userid.value = res.data._id
					}
				});
				setTimeout(() => {
					// uni.connectSocket({
					// 	url: `ws://localhost:8080/ws?id=${userid.value}`
					// });
				})
				getlist()
			})
			uni.onSocketOpen(function(res) {
				console.log('WebSocket连接已打开！');
			});
			uni.onSocketError(function(res) {
				console.log('WebSocket连接打开失败，请检查！');
			});

			uni.request({
				url: 'http://127.0.0.1:3366/tyh/userlist',
				success: (res) => {
					datas.data = res.data.data
					this.text = 'request success';
				}
			})

			function getlist() {
				// setInterval(() => {
					uni.request({
						url: 'http://127.0.0.1:3366/tyh/chatlist',
						method: 'GET',
						success: (res) => {
							datas.data.forEach((nitem) => {
								let total = 0
								res.data.data.forEach((witem) => {
									if (nitem._id === witem.my_id && !witem
										.is_read) {
										total += 1
										// let total = parseInt(nitem.total) + 1
										// uni.request({
										// 	url: 'http://127.0.0.1:3366/tyh/chatadd',
										// 	method: 'POST',
										// 	data: {
										// 		id: nitem._id,
										// 		total:total
										// 	},
										// 	success: (res) => {
										// 		console.log(res.data.data)
										// 	}
										// })
									} else {
										console.log(false)
									}
									nitem.total = total
								})
							})
							this.text = 'request success';
						}
					})
				// }, 2000)
			}

			function handlepath(item) {
				// uni.request({
				// 	url: `http://127.0.0.1:3366/tyh/webscoketlist?id=${item._id}`,
				// 	method: 'GET',
				// 	// data: {
				// 	// 	user_id: item._id,
				// 	// },
				// 	// success: (res) => {
				// 	// console.log(res,'333333333')
				// 	// datas.data = res.data.data
				// 	// this.text = 'request success';
				// 	// },
				// })
				uni.navigateTo({
					url: `/pages/web/tyh/chatpage?id=${item._id}&name=${item.username}&img=${item.avater}`
				})
			}
			return {
				datas,
				handlepath,
				userid
			}
		}
	}
</script>

<style>
</style>